package com.woniu.user.service.impl;

import com.woniu.common.pojo.dto.user.PayDto;
import com.woniu.common.util.SnowflakeIdWorker;
import com.woniu.user.entity.BalanceRecords;
import com.woniu.user.entity.PayOrder;
import com.woniu.user.mapper.BalanceRecordsMapper;
import com.woniu.user.mapper.PayOrderMapper;
import com.woniu.user.mapper.UserInfoMapper;
import com.woniu.user.service.IPayOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 贾玉亮
 * @since 2023-01-05
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private BalanceRecordsMapper balanceRecordsMapper;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private SnowflakeIdWorker sfw;
    @Override
    @Transactional
    public int payForBalance(PayDto payDto) {
        //1.扣除用户表中的余额
        BigDecimal balance=userInfoMapper.getBalanceByUserId(payDto.getFkUserId());
        int i = balance.compareTo(payDto.getAmount());
        if (i == -1){
            //余额不足
            return 0;
        }
        //2.余额足够,进行扣款
        balance=balance.subtract(payDto.getAmount());
        int num = userInfoMapper.modifyBalance(balance,payDto.getFkUserId());

        if (num > 0){
            //3.余额修改成功
            //4.余额操作记录表新增
            BalanceRecords balanceRecords = new BalanceRecords();
            balanceRecords.setFkUserId(payDto.getFkUserId());
            balanceRecords.setMoney(payDto.getAmount());
            //支出为 "2"
            balanceRecords.setOperate("2");
            balanceRecordsMapper.insert(balanceRecords);
            //5.支付订单表新增
            PayOrder payOrder = new PayOrder();
            BeanUtils.copyProperties(payDto,payOrder);
            payOrder.setPayNum("P"+sfw.nextId());
            payOrderMapper.insert(payOrder);
            return 1;
        }

        return 2;
    }

    @Override
    public int payForBank(PayDto payDto) {
        return 2;
    }
}
